# -*- coding: utf-8 -*-
import pygame, random, sys, time, pickle
import colorsnew as colorlib
from spites_util import *
import get_input

loop_return = True
#theme = None
#point = None
#game_over = None
Highscore = [0, 0, 0, 0, 0]

myColorScheme = ColorScheme()

# the main game class. The stuff happens here!    
# actually, far to much stuff happens here.
# It should be splitted up into functions
# All window-relatet things should go to a Window class
class Game():
    # initializes everything
    # creates a (width x height) - window 
    # put's 50 blocks on the screen
    def __init__(self, player = 1):
        self.player = player
        # just creates the window, doesn't draw it

        self.screen = pygame.display.get_surface()      
        pygame.mouse.set_visible(MOUSE_GUIDANCE_MODE)

        # Blocks.
        # cretes a new list of sprites
        self.block_list = pygame.sprite.RenderPlain()

        # another list of sprites that will contain
        # all sprites, including player
        # Will be used later to draw it all
        self.all_sprites_list = pygame.sprite.RenderPlain()
        
        # the bad blocks
        self.bad_block_list = pygame.sprite.RenderPlain()
        
        # create 50 blocks, some of the bad
        for i in range(100):
            #if random.randrange(100) < bad_blocks_prob:
            if len(self.bad_block_list) < NUM_BAD_BLOCKS:
                # the bad block is placed in the bad block list
                block = BadBlock(colorlib.random_color('black'),20,15)
                self.bad_block_list.add(block)
                
            else:
                # a normal block
                block = Block(colorlib.random_color('light','red'), 20 + random.randrange(-8,9), 15 + random.randrange(-7,8))
                self.block_list.add(block)
            # random coordinates for the blocks, both bad and not
            block.rect.x = random.randrange(WIDTH)
            block.rect.y = random.randrange(HEIGHT)
            
            # add the block to the list of blocks
            self.all_sprites_list.add(block)
        
        # player block
        # self.player1 is a block which is also a Sprite
        # red block!
        #self.player1 = Block(myColorScheme.red, 25, 20)
        self.player1 = Block(colorlib.random_color('red'),25,20)
        # middle of the screen
        self.player1.rect.x = (WIDTH//(1+self.player))
        self.player1.rect.y = (HEIGHT//2)
        # is in the list of all blocks
        self.all_sprites_list.add(self.player1)
        if self.player == 2:
            self.player2 = Block(colorlib.random_color('red'),25,20)
            self.player2.rect.x = (WIDTH//2)
            self.player2.rect.y = (HEIGHT//2)
            self.all_sprites_list.add(self.player2)
        # movement
        self.player1_speed = [0.0, 0.0]
        
        # are we done yet? 
        self.done = False
        self.loop_return = True
        
        # will be used later to set the update speed
        self.clock = pygame.time.Clock()
        
        self.score = 0
        
        # not entirely sure what this does
        # don't think it's ever used
        #self.pos = pygame.mouse.get_pos()
        
        # will be set to true
        # if you hold down some key
        self.down = False
        self.up = False
        self.left = False
        self.right = False
        self.brake = False
        # does extra stuff on the first game loop
        self.first_loop = True
        self.speed_mode = 2
        # creates two channels to play sounds on, bgm for music
        # and sxf for effects
        self.bgm = pygame.mixer.Channel(0)
        self.sxf = pygame.mixer.Channel(1)
        # starts the backgrund theme
        if self.bgm.get_sound() != theme: self.bgm.play(theme,-1)

    # spawns new random color blocks instead of the killed ones
    def spawn_new(self):
        # how many do we have?
        if NUM_BLOCKS > len(self.block_list):
            block = Block(colorlib.random_color('light','red'),block_dimensions[0],
                          block_dimensions[1])
            block.rect.x = random.randrange(WIDTH) # there is probably a screen.dimensions or smth
            block.rect.y = random.randrange(0, 20)
            self.block_list.add(block)
            self.all_sprites_list.add(block)
            if DEBUG:
                print ("Block spawned at ", block.rect.x, block.rect.y)
  
    def draw(self, max_x_pos = WIDTH, max_y_pos = HEIGHT):
        # fills the screen with color and 
        # updates block position
        # we should have a move(self)
        #if DEBUG: print (self.player1.rect.x, self.player1.rect.y, self.player1_speed[0], self.player1_speed[1])
        # 
        self.screen.fill(myColorScheme.white)
        
        # player block comes back on the other side
        # if it moves outside of the screen
        if (self.player1.rect.x > max_x_pos):
            self.player1.rect.x = 0
            
        if (self.player1.rect.x < 0):
            self.player1.rect.x = max_x_pos
        
        if (self.player1.rect.y > max_y_pos):
            self.player1.rect.y = 0
        if (self.player1.rect.y < 0):
            self.player1.rect.y = max_y_pos
        
        self.player1.rect.x += self.player1_speed[0]
        self.player1.rect.y += self.player1_speed[1]
        
    def collide(self):
        blocks_hit_list = pygame.sprite.spritecollide(self.player1,
                                                      self.block_list,
                                                      True)
        bad_blocks_hit_list = pygame.sprite.spritecollide(self.player1, 
                                                          self.bad_block_list,
                                                          False)
        if len(bad_blocks_hit_list) > 0:
            global loop_return
            self.loop_return = False
            #sys.exit(0)
        
        return blocks_hit_list
    
    
    def creep_around(self):
        for sprite in self.block_list:
            
            sprite.move(random.randrange(-2, 3), 
                        random.randrange(-2, 3), self.player1.rect.x, self.player1.rect.y)
            
        for sprite in self.bad_block_list:
            sprite.move(self.player1.rect.x, self.player1.rect.y)

    def loop(self):
        global loop_return
        get_input.get_input(self)
        
        new_score = len(self.collide())
        
        if new_score > 0:
            self.score += new_score
            self.sxf.play(point) 
            
        self.creep_around()
        self.spawn_new()
        if self.score % max_score == max_score-1 and new_score > 0:
            myColorScheme.newColors()
            
        
        

        self.draw()
        self.all_sprites_list.draw(self.screen)
        self.clock.tick(10)
        speed = round((P.abs_speed(self.player1_speed)), 3)
        font = pygame.font.Font(None, 20 + int(speed))
        if (speed > 30):
            text = font.render(str(speed),
                               1,
                               (255, 0, 0))
        else :
            text = font.render(str(speed),
                               1,
                               myColorScheme.black)
        
        textpos = text.get_rect()
        textpos.top = HEIGHT - 200
        
        font2 = pygame.font.Font(None, 36)
        text2 = font2.render(str(self.score), 1, myColorScheme.black)
        textpos2 = text.get_rect()
        textpos2.top = HEIGHT-30
        
        self.screen.blit(text, textpos)
        self.screen.blit(text2, textpos2)
        pygame.display.flip()
        
        if self.first_loop:
            time.sleep(1)
            self.first_loop = False
        if not(self.loop_return):
            self.bgm.play(game_over)
            print ("Du fick ", self.score, "poäng!")
            if (self.score > Highscore[0]):
                self.new_highscore()
            time.sleep(4)
            return False
        else : return True

    def new_highscore(self):
        font = pygame.font.Font(None,36)
        text = font.render('New Highscore!',1,myColorScheme.black)
        self.screen.blit(text,(0,HEIGHT-60))
        pygame.display.flip()
        Highscore[0] = self.score
        Highscore.sort()
        f = open('highscore.spites','wb')
        pickle.dump(Highscore,f)
        f.close()
        
def main():
    global theme,point,game_over,Highscore
    
    # loads the highscore from highscore.spites
    try:
        f = open('highscore.spites','rb')
        Highscore = pickle.load(f)
        f.close()
    except IOError:
        Highscore = [0,0,0,0,0]

    ljud = pygame.mixer.Sound
    pygame.font.init()
    pygame.mixer.init()
    theme = ljud('Theme.ogg')
    point = ljud('point.wav')
    game_over = ljud('game_over.ogg')
    c = 0
    while True:
        global loop_return
        loop_return = True
        newGame = Game()
        
        while newGame.loop():
            pass
